<template>
  <div class="post-detail-page">
    <NavBar />
    
    <div class="main-content" v-if="!postsStore.loading">
      <div class="container">
        <article class="post-article" v-if="postsStore.currentPost">
          <!-- 文章头部 -->
          <header class="post-header">
            <div class="post-meta">
              <div class="author-info" v-if="postsStore.currentPost.author">
                <el-avatar :src="postsStore.currentPost.author.avatar_url" :size="40">
                  {{ postsStore.currentPost.author.username.charAt(0).toUpperCase() }}
                </el-avatar>
                <div class="author-details">
                  <span class="author-name">{{ postsStore.currentPost.author.username }}</span>
                  <span class="post-date">{{ formatDate(postsStore.currentPost.published_at || postsStore.currentPost.created_at) }}</span>
                </div>
              </div>
              <div class="author-info" v-else>
                <el-avatar :size="40">匿名</el-avatar>
                <div class="author-details">
                  <span class="author-name">匿名用户</span>
                  <span class="post-date">{{ formatDate(postsStore.currentPost.published_at || postsStore.currentPost.created_at) }}</span>
                </div>
              </div>
              
              <div class="post-stats">
                <span class="stat-item">
                  <el-icon><View /></el-icon>
                  <span class="stat-label">浏览</span>
                  <span class="stat-value">{{ postsStore.currentPost.view_count }}</span>
                </span>
                <span class="stat-item">
                  <el-icon><Like /></el-icon>
                  <span class="stat-label">点赞</span>
                  <span class="stat-value">{{ postsStore.currentPost.like_count }}</span>
                </span>
              </div>
            </div>
            
            <h1 class="post-title">{{ postsStore.currentPost.title }}</h1>
            
            <div class="post-tags" v-if="postsStore.currentPost.tags.length > 0">
              <el-tag
                v-for="tag in postsStore.currentPost.tags"
                :key="tag.id"
                class="post-tag"
              >
                {{ tag.name }}
              </el-tag>
            </div>
          </header>
          
          <!-- 文章内容 -->
          <div class="post-content">
            <div class="content-html" v-html="postContent"></div>
          </div>
          
          <!-- 文章操作 -->
          <div class="post-actions">
            <el-button type="primary" @click="likePost" :loading="liking">
              <el-icon><Like /></el-icon>
              点赞 ({{ postsStore.currentPost.like_count }})
            </el-button>
            
            <el-button @click="sharePost">
              <el-icon><Share /></el-icon>
              分享
            </el-button>
            
            <el-button v-if="canEdit" @click="editPost">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            
            <el-button v-if="canEdit" type="danger" @click="deletePost">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </article>
        
        <!-- 评论区域 -->
        <div class="comments-section">
          <h3 class="comments-title">评论</h3>
          
          <!-- 发表评论 -->
          <div class="comment-form" v-if="userStore.isLoggedIn">
            <el-form @submit.prevent="submitComment">
              <el-input
                v-model="commentContent"
                type="textarea"
                placeholder="写下你的评论..."
                :rows="3"
                maxlength="1000"
                show-word-limit
              />
              <div class="comment-actions">
                <el-button type="primary" @click="submitComment" :loading="commenting">
                  发表评论
                </el-button>
              </div>
            </el-form>
          </div>
          
          <!-- 评论列表 -->
          <div class="comments-list">
            <div v-if="comments.length === 0" class="no-comments">
              <el-empty description="暂无评论" />
            </div>
            
            <div v-else>
              <CommentItem
                v-for="comment in comments"
                :key="comment.id"
                :comment="comment"
                @reply="handleReply"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePostsStore } from '@/stores/posts'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { marked } from 'marked'
import api from '@/utils/api'
import NavBar from '@/components/NavBar.vue'
import Footer from '@/components/Footer.vue'
import CommentItem from '@/components/CommentItem.vue'
import type { Comment } from '@/types'

const route = useRoute()
const router = useRouter()
const postsStore = usePostsStore()
const userStore = useUserStore()

const commentContent = ref('')
const comments = ref<Comment[]>([])
const liking = ref(false)
const commenting = ref(false)


const postContent = computed(() => {
  if (!postsStore.currentPost) return ''
  return marked(postsStore.currentPost.content)
})

const canEdit = computed(() => {
  if (!postsStore.currentPost || !userStore.user || !postsStore.currentPost.author) return false
  return postsStore.currentPost.author.id === userStore.user.id || userStore.isAdmin
})

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const loadPost = async () => {
  try {
    const { id } = route.params
    
    if (id && typeof id === 'string') {
      await postsStore.fetchPost(id)
      // 加载评论
      await loadComments()
    } else {
      throw new Error('缺少文章标识')
    }
  } catch (error) {
    console.error('加载文章失败:', error)
    ElMessage.error('文章不存在或已被删除')
    router.push('/posts')
  }
}

const loadComments = async () => {
  if (!postsStore.currentPost) return
  
  try {
    const response = await api.get(`/posts/${postsStore.currentPost.id}/comments`)
    // 确保每个评论都有replies字段
    comments.value = response.data.map((comment: any) => ({
      ...comment,
      replies: comment.replies || []
    }))
  } catch (error) {
    console.error('加载评论失败:', error)
  }
}

const likePost = async () => {
  if (!postsStore.currentPost) return
  
  try {
    liking.value = true
    
    // 调用点赞API
    await api.post(`/posts/${postsStore.currentPost.id}/like`)
    
    // 更新本地计数
    postsStore.currentPost.like_count += 1
    ElMessage.success('点赞成功')
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('点赞失败，请重试')
  } finally {
    liking.value = false
  }
}

const sharePost = () => {
  if (navigator.share) {
    navigator.share({
      title: postsStore.currentPost?.title,
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href)
    ElMessage.success('链接已复制到剪贴板')
  }
}

const editPost = () => {
  if (postsStore.currentPost) {
    router.push(`/edit/${postsStore.currentPost.id}`)
  }
}

const deletePost = async () => {
  if (!postsStore.currentPost) return
  
  try {
    await ElMessageBox.confirm(
      '确定要删除这篇文章吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 调用删除API
    await postsStore.deletePost(postsStore.currentPost.id)
    
    ElMessage.success('文章删除成功')
    router.push('/posts')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除文章失败，请重试')
    }
  }
}

const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  if (!postsStore.currentPost) {
    ElMessage.error('文章信息错误')
    return
  }
  
  try {
    commenting.value = true
    
    // 调用发表评论API
    const response = await api.post(`/posts/${postsStore.currentPost.id}/comments`, {
      content: commentContent.value.trim()
    })
    
    // 重新加载评论列表
    await loadComments()
    
    ElMessage.success('评论发表成功')
    commentContent.value = ''
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('评论发表失败，请重试')
  } finally {
    commenting.value = false
  }
}

const handleReply = (comment: Comment) => {
  if (comment.author) {
    commentContent.value = `@${comment.author.username} `
  }
}

onMounted(() => {
  loadPost()
})
</script>

<style scoped>
.post-detail-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 2rem 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.post-article {
  background: white;
  border-radius: 16px;
  padding: 2.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.post-article:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.post-header {
  margin-bottom: 2rem;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 600;
  color: #333;
  font-size: 0.9rem;
}

.post-date {
  font-size: 0.8rem;
  color: #666;
}

.post-stats {
  display: flex;
  gap: 1.5rem;
  color: #666;
  font-size: 0.875rem;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.stat-item:hover {
  background: #e9ecef;
}

.stat-label {
  font-size: 0.75rem;
  color: #6c757d;
}

.stat-value {
  font-weight: 600;
  color: #495057;
}

.post-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 1rem;
  line-height: 1.3;
}

.post-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.post-tag {
  margin: 0;
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
  transition: all 0.2s ease;
}

.post-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
  border-color: #337ecc !important;
}

/* 覆盖Element Plus的默认样式 */
.post-tags .el-tag {
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.post-tags .el-tag--primary {
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
}

.post-tags .el-tag--light {
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
}

.post-content {
  margin-bottom: 2rem;
}

.content-html {
  line-height: 1.5;
  color: #333;
  font-size: 0.9rem;
}

.content-html :deep(h1),
.content-html :deep(h2),
.content-html :deep(h3),
.content-html :deep(h4),
.content-html :deep(h5),
.content-html :deep(h6) {
  margin-top: 2rem;
  margin-bottom: 1rem;
  font-weight: 600;
  line-height: 1.25;
}

.content-html :deep(h1) {
  font-size: 1.4rem;
}

.content-html :deep(h2) {
  font-size: 1.2rem;
}

.content-html :deep(p) {
  margin-bottom: 1rem;
}

.content-html :deep(blockquote) {
  margin: 1rem 0;
  padding: 0 1rem;
  color: #6a737d;
  border-left: 4px solid #dfe2e5;
}

.content-html :deep(code) {
  padding: 2px 4px;
  background: #f6f8fa;
  border-radius: 3px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 85%;
}

.content-html :deep(pre) {
  padding: 1rem;
  background: #f6f8fa;
  border-radius: 6px;
  overflow: auto;
  margin: 1rem 0;
}

.content-html :deep(pre code) {
  padding: 0;
  background: transparent;
}

.content-html :deep(img) {
  max-width: 60%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 1rem auto;
  display: block;
}

.content-html :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 1rem 0;
  overflow-x: auto;
  display: block;
  white-space: nowrap;
}

.content-html :deep(table th),
.content-html :deep(table td) {
  border: 1px solid #e5e7eb;
  padding: 8px 12px;
  text-align: left;
}

.content-html :deep(table th) {
  background: #f9fafb;
  font-weight: 600;
}

.post-actions {
  display: flex;
  gap: 1rem;
  padding-top: 2rem;
  border-top: 1px solid #e5e7eb;
}

.comments-section {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comments-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 1.5rem;
}

.comment-form {
  margin-bottom: 2rem;
}

.comment-actions {
  margin-top: 1rem;
  text-align: right;
}

.loading-container {
  padding: 2rem;
}

@media (max-width: 768px) {
  .post-article,
  .comments-section {
    padding: 1rem;
  }
  
  .post-title {
    font-size: 2rem;
  }
  
  .post-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .post-actions {
    flex-direction: column;
  }
}
</style>
